package com.liu.dw.common.word;

import com.liu.dw.mapper.word.WordMapper;
import com.liu.dw.vo.word.Wdoument;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @version 1.0
 * @author： LiuWeiGang
 * @date： 2021-12-04 09:42
 * 文档解析封装类
 */

public  class WordUtils {

    @Autowired
    private static WordMapper wordMapper;

/**
* 将解析word2007   .docx的代码封装
* @param file
*/
  public static void word2007(MultipartFile file) throws IOException {
      //存入数据库的路径
      String pathfile = "/Users/liuweigang/Desktop/temptest/word/wor";
      String textFileName=file.getOriginalFilename();
      File uFile = new File("tempFile.docx");//创建一个临时文件
      if (!uFile.exists()) {
          uFile.createNewFile();
      }
      Map<Integer,String> wordMap = new LinkedHashMap();//创建一个map对象存放word中的内容
      //解析文件中的文字
      FileCopyUtils.copy(file.getBytes(), uFile);//复制文件内容
      OPCPackage opcPackage = POIXMLDocument.openPackage("tempFile.docx");//包含所有POI OOXML文档类的通用功能，打开一个文件包。
      XWPFDocument document = new XWPFDocument(opcPackage);//使用XWPF组件XWPFDocument类获取文档内容
      List<XWPFParagraph> paras = document.getParagraphs();
      int i = 1;
      for (XWPFParagraph paragraph : paras) {
          String words = paragraph.getText();
          //将第几行和每行的数据存到map中
          wordMap.put(i, words);
          i++;
      }
      //向数据库中存入当前资源的路径
      String er = pathfile  +textFileName;
      //存放到用户ID中
      String fileName=file.getOriginalFilename();
      System.out.println(fileName);
      String replace = fileName.replace(".", ",");
      System.out.println(replace);
      String[] split = replace.split(",");
      String s = split[0];
      Set<Map.Entry<Integer, String>> entries = wordMap.entrySet();
      for (Map.Entry<Integer, String> entry : entries) {
          Integer key = entry.getKey();
          String value = entry.getValue();
          System.out.println("第"+key+":"+value);
          Wdoument wdoument = new Wdoument();
          wdoument.setWpath(er);
          wdoument.setWname(textFileName);
         wordMapper.importWord(wdoument);
      }


      /**
       * 解析word2007中的表格
       */
      Iterator<XWPFTable> its = document.getTablesIterator();
      String[] strings = new String[4];
      Map<Integer,String> stringMap = new HashMap<>();
      String ns = "";
      int dfs = 0;
      int ind = 0;
      while (its.hasNext()){
          ind++;
          XWPFTable table = (XWPFTable) its.next();
          //行
          int rcount = table.getNumberOfRows();
          for (int ix = 0; ix < rcount; ix++){
              XWPFTableRow row = table.getRow(ix);
              //列
              List<XWPFTableCell> cells = row.getTableCells();
              int len = cells.size();
              for(int j = 0;j < len;j++){
                  XWPFTableCell xc = cells.get(j);
                  String sc = xc.getText();
                  strings[j] = sc;
              }
              StringBuffer sb = new StringBuffer();
              for(int jd = 0; jd < strings.length; jd++){
                  sb. append(strings[jd]);
              }
              ns = sb.toString();
              dfs++;
              stringMap.put(dfs,ns);
          }

          Set<Map.Entry<Integer, String>> entries1 = stringMap.entrySet();
          for (Map.Entry<Integer,String> entry: entries1) {
              Integer key = entry.getKey();
              String value = entry.getValue();
              System.out.println("第"+key+"行"+","+value);
          }
      }

      //word中对图片解析，并将图片存入数据库
      List<XWPFPictureData> allPictures = document.getAllPictures();
      String imagePath = "/Users/liuweigang/Desktop/temptest/temp";
      String uuids = UUID.randomUUID().toString().replace("-", "").toLowerCase();
      System.out.println("------------------------------------------");
      for (XWPFPictureData picture : allPictures) {
          byte[] by = picture.getData();
          System.out.println(Arrays.toString(by));
          FileOutputStream stream1 = new FileOutputStream(imagePath + uuids + picture.getFileName());
          stream1.write(by);
          //向数据库中存入图片的完整路径
          String path =  imagePath + uuids + picture.getFileName();
//          ImageVo imageVo = new ImageVo();
//          imageVo.setImages(by);
//          imageVo.setImagename(textFileName);
//          imageVo.setPath(path);
//          wordMapper.image(imageVo);
      }

  }




    public  static  void word2003(MultipartFile file) throws IOException {
        Map<Integer,String> map = new LinkedHashMap();//创建一个map对象存放word中的内容
        String textFileName=file.getOriginalFilename();
        String suffix = textFileName.substring(textFileName.lastIndexOf("."));
        try {
           if (suffix.endsWith(".doc")) {
               InputStream fis = file.getInputStream();
               WordExtractor wordExtractor = new WordExtractor(fis);//使用HWPF组件中WordExtractor类从Word文档中提取文本或段落
               int i=1;
               for(String words : wordExtractor.getParagraphText()){//获取段落内容
                   map.put(i,words);
                   i++;
               }
               Set<Map.Entry<Integer, String>> entries = map.entrySet();
               for (Map.Entry<Integer, String> entry: entries) {
                   Integer key = entry.getKey();
                   String value = entry.getValue();
                   System.out.println("解析word2003"+": 第"+key +":"+value);
               }
           }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
